package com.youlai.boot.common.listener;

import cn.hutool.core.util.ReflectUtil;
import com.mybatisflex.annotation.InsertListener;
import com.youlai.boot.core.security.util.SecurityUtils;
import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Method;

@Log4j2
public class CreatedByListener implements InsertListener {
    @Override
    public void onInsert(Object entity) {
        Method createdBy = ReflectUtil.getMethodByName(entity.getClass(), "setCreatedBy");
        Method updatedBy = ReflectUtil.getMethodByName(entity.getClass(), "setUpdatedBy");

        if (SecurityUtils.getUserId() != null) {
            if (createdBy != null) {
                ReflectUtil.invoke(entity, "setCreatedBy", SecurityUtils.getUserId());
            }

            if (updatedBy != null) {
                ReflectUtil.invoke(entity, "setUpdatedBy", SecurityUtils.getUserId());
            }
        }
    }
}
